package com.cat.yygh.order.controller;

import com.cat.yygh.common.result.R;
import com.cat.yygh.enums.PaymentTypeEnum;
import com.cat.yygh.order.service.PaymentService;
import com.cat.yygh.order.service.WeiPayService;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/user/order/wx")
public class WeiPayController {
    @Autowired
    private WeiPayService weiPayService;
    @Autowired
    private PaymentService paymentService;
    @GetMapping("/{orderId}")
    public R createNative(
            @ApiParam(name = "orderId", value = "订单id", required = true)
            @PathVariable Long orderId){
        Map map = weiPayService.createNative(orderId);
        return R.ok().data(map);
    }
    @GetMapping("/status/{orderId}")
    public R getPayStatus(@PathVariable Long orderId){
        Map<String,String> resultMap = weiPayService.queryPayStatus(orderId);
        if (resultMap == null) {//出错
            return R.error().message("支付出错");
        }
        if ("SUCCESS".equals(resultMap.get("trade_state"))) {//如果成功
            //更改订单状态，处理支付结果
            String out_trade_no = resultMap.get("out_trade_no");
            paymentService.paySuccess(out_trade_no, PaymentTypeEnum.WEIXIN.getStatus(), resultMap);
            return R.ok().message("支付成功");
        }
        return R.ok().message("支付中");
    }
}
